from flask import (
    Flask,
    url_for,
    request,
    redirect,
    session,
    after_this_request,
    current_app,
    g,
    Response,
    make_response,
    jsonify,
)
from werkzeug.routing import BaseConverter

app = Flask(__name__)
app.secret_key = "Your_secret_key&^52@!"

"""
2.1 注册路由
"""
# @app.route('/index')  # 通过装饰器使用route()方法注册路由，并定义的URL为/index
# def index():
#     return f'<h1>这是首页！</h1>'

# def index_new():
#     return f'<h1>这是首页！</h1>'
# # 使用add_url_rule()方法注册路由，并绑定到index_new()函数
# app.add_url_rule(rule='/index', view_func=index_new)


# @app.route("/homepage")
# @app.route("/index")
# def index():
#     return f"<h1>这是首页！</h1>"


"""
2.2.1 URL传递参数的方式
"""
# @app.route('/<page>')   	# URL中传递的参数为page
# def page_num(page):    	# 将URL中的参数传递到视图函数中
#     print(type(page))
#     return f'当前为第{page}页'


"""
2.2.2 为参数指定转换器
"""
# 内置转换器
# @app.route('/<int:page>')
# def page_num(page):
#     return f'当前为第{page}页'

# 自定义转换器
# class MobileConverter(BaseConverter):  # 自定义类型转换器
#     regex = "1[3-9]\d{9}$"  # 定义匹配手机号码的规则
# app.url_map.converters["mobile"] = MobileConverter  # 添加到转换器字典列表
# @app.route("/user/<mobile:mobile>")
# def index(mobile):
#     return f'手机号为：{mobile}'


"""
2.3.1 指定请求方式
"""
# @app.route('/login', methods=['GET'])
# def login():
#     pass
# @app.route('/login', methods=['GET', 'POST'])
# def login():
#     pass
# @app.post('/login')
# def login():
#     pass


"""
2.3.2 请求钩子
"""
# @app.before_first_request
# def before_first_request():
#     print('这是请求钩子before_first_request注册的函数')
# @app.before_request
# def before_request():
#     print('这是请求钩子before_request注册的函数')
# @app.route('/index')
# def index():
#     print('hello flask')
#     @after_this_request
#     def after_this_request_func(response):
#         print('这是请求钩子after_this_request注册的函数')
#         return response
#     return 'hello flask'
# @app.after_request
# def after_request(response):
#     print('这是请求钩子after_request注册的函数')
#     return response
# @app.teardown_request
# def teardown_request(error):
#     print('这是请求钩子teardown_request注册的函数')


"""
2.3.3 上下文
"""
# 1. 请求上下文
# @app.route('/index')
# def index():
#     user_agent = request.user_agent  # 获取浏览器标识信息
#     return f'{user_agent}'

# app.secret_key = 'Your_seccret_key&^52@!'   		# 设置secret_key的值
# @app.route('/index')
# def index():
#     if 'username' in session:
#         return f'你好：{session.get("username")}'
#     return '请登录'
# @app.route('/login', methods=['GET', 'POST'])
# def login():
#     if request.method == 'POST':
#         session['username'] = request.form['username'] # 设置session值
#         return '登录成功'
#     return '''
#         <form method="post">
#             <p><input type=text name=username>
#             <p><input type=submit value='登录'>
#         </form>
#     '''

# 2. 应用上下文
# app.secret_key = 'Your_seccret_key&^52@!'
# @app.route('/')
# def index():
#     # 通过current_app对象获取密钥
#     return f'{current_app.secret_key}'

# @app.route('/')
# def get_user():
#     user_id = '001'           	# 设置用户id
#     user_name = 'flask'    		# 设置用户名称
#     g.user_id = user_id           # 将用户id保存到g对象中
#     g.user_name = user_name 		# 将用户名称保存到g对象中
#     result = db_query()
#     return f'{result}'
# def db_query():
#     user_id = g.user_id    		# 使用g对象获取用户id
#     user_name = g.user_name  		# 使用g对象获取用户名称
#     return f'{user_id}:{user_name}'

"""
2.4.2 生成响应
"""
# @app.route('/index')
# def index():
#     # 使用Response类的构造方法生成响应对象，设置状态码为201，响应类型为text/html
#     resp = Response(response='Python&Flask',status=201, content_type='text/html;charset=utf-8')
#     return resp
#
# @app.route('/index')
# def index():
#     res = make_response('Python&Flask',201, {'content-type':' text/html;charset=utf-8'})
#     return res
#
# @app.route('/response')
# def resp():
#     res = make_response(jsonify({'Python':'Flask'}),202)
#     return res


"""
2.5	URL反向解析
"""
# @app.route('/hello/flask')
# def greet():
#     return f"{url_for('greet')}"   # 反向解析视图函数greet()对应的URL
#
# @app.route('/hello/<name>')
# def greet(name):
#     return f"{url_for('greet',name=name)}"
#
# @app.route('/hello/<name>')
# def greet(name):
#     # 将age=20添加到URL地址中
#     return f"{url_for('greet',name=name, age=20)}"


"""
2.6	页面重定向
"""
app.secret_key = "Your_secret_key&^52@!"


@app.route("/index")
def index():
    if "username" in session:
        return f'你好：{session.get("username")}'  # 返回欢迎信息
    return redirect(url_for("login"))  # 页面重定向到登录页面


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        session["username"] = request.form["username"]
        return redirect(url_for("index"))  # 页面重定向到欢迎页面
    # 当发送GET请求时，页面显示输入框和登录按钮
    return """
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=登录>
        </form>
    """


if __name__ == "__main__":
    app.run()
